package com.k7.mobile.platform.bo.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import com.k7.mobile.platform.bo.ISearchQueryBO;
import com.k7.mobile.platform.dataobject.GramDO;
import com.k7.mobile.platform.dataobject.QueryDO;
import com.k7.mobile.platform.util.DateTimeUtil;
import com.qike.java.util.HttpClientUtil;

public class SearchQueryBOImpl extends BaseBOImpl implements  ISearchQueryBO{

	public String gameSearchUrl = null;
	
	
	public void setGameSearchUrl(String gameSearchUrl) {
		this.gameSearchUrl = gameSearchUrl;
	}



	@Override
	public List<GramDO> searchGame(QueryDO query) throws Exception {
		 
		 StringBuffer urlBuf = new StringBuffer();
		 if(query.getKeyword()!=null && !StringUtils.isBlank(query.getKeyword())){
			 if(urlBuf.length() > 0)
				 urlBuf.append("&");
			 urlBuf = urlBuf.append("k="+ query.getKeyword());
		 }
		 if(query.getTypeId()!=null ){
			 if(urlBuf.length() > 0)
				 urlBuf.append("&");
			 urlBuf = urlBuf.append("typeid="+ query.getTypeId());
		 }
		 if(query.getBtype()!=null ){
			 if(urlBuf.length() > 0)
				 urlBuf.append("&");
			 urlBuf = urlBuf.append("classid="+ query.getBtype());
		 }
		 if(query.getLanguageId()!=null ){
			 if(urlBuf.length() > 0)
				 urlBuf.append("&");
			 urlBuf = urlBuf.append("langid="+ query.getLanguageId());
		 }
		 if(query.getPayId()!=null ){
			 if(urlBuf.length() > 0)
				 urlBuf.append("&");
			 urlBuf = urlBuf.append("payid="+ query.getPayId());
		 }
	
		 if(urlBuf.length() > 0)
				 urlBuf.append("&");
		 urlBuf = urlBuf.append("pageSize="+ query.getPerPageSize());
		 if(urlBuf.length() > 0)
			 urlBuf.append("&");
		 if(query.getToPage() ==0)
			 urlBuf = urlBuf.append("page=1");
		 else
			 urlBuf = urlBuf.append("page="+ query.getToPage());
		 if(urlBuf.length() > 0)
			 urlBuf.insert(0,"&");
		 urlBuf.insert(0, gameSearchUrl);
		 
		 List<GramDO> list =  new  ArrayList<GramDO>();
		 
		 try{
				String response = HttpClientUtil.get(urlBuf.toString());
				JSONObject rootJson =  JSONObject.fromObject(response);
				if(rootJson != null){
					int status = rootJson.getInt("status");
					if(status == 0)
						return list;
					JSONObject dataObject = rootJson.getJSONObject("data");
					if(dataObject != null){
						query.setTotalItem(dataObject.getInt("totalNum"));
						query.validatePageInfo();
						JSONArray gameArray = dataObject.getJSONArray("list");
						if(gameArray != null){
							for(int i=0;i<gameArray.size();i++){
								JSONObject gameObject = gameArray.getJSONObject(i);
								GramDO gram =new GramDO();
								gram.setId(gameObject.getLong("gid"));
								gram.setVname(gameObject.getString("vname"));
								gram.setIcon(gameObject.getString("icon"));
								gram.setBtype(gameObject.getInt("classid"));
								gram.setLanguage(gameObject.getInt("langid"));
								gram.setPayType(gameObject.getString("paytype"));
								gram.setStype(gameObject.getString("typeid"));
								gram.setScore(gameObject.getInt("score"));
								gram.setMoney(gameObject.getDouble("money"));
								gram.setUtime(DateTimeUtil.getFormatDateTime_CN(gameObject.getString("utime")));
								gram.setCdate(DateTimeUtil.getFormatDate_CN(gameObject.getString("cdate")));
								gram.setAverage(gameObject.getDouble("average"));
								gram.setPlNum(gameObject.getInt("pl_num"));
								gram.setDownNum(gameObject.getInt("down_num"));
								list.add(gram);
							}
						}
					}
				}
				return list;
			}catch(Exception e){
				log.error("UserBOImpl:getAllFriends 获取好友列表失败.", e);
				//throw new BOException("获取好友列表失败.", e);
			}
		 return list;
	}



/**
 * 删除游戏索引
 * @param gramDO
 */	
	/*
public  void deleteGramIndex(GramDO gramDO)throws Exception{
	IndexReader reader=null;
	try{
		
	 Directory dir = FSDirectory.open(new File(gameIndexPath));  
	 reader = IndexReader.open(dir,false);  
	 Term term = new Term("GRAMID",gramDO.getId().toString());  	  
	 reader.deleteDocuments(term);      
     reader.flush();  

	}catch(Exception e){
		log.error("SearchQueryBOImpl:删除游戏索引失败", e);
		throw e;
	}finally{
		reader.close();
	}
}
*/
/**
 * 
 * @param searchIndex 需要检索的字段
 * @param keyword  关键词
 * @return List bars 
 * @throws Exception
 */
private List<GramDO> searchQueryGram(String url,QueryDO queryDO) throws Exception{
		List<GramDO> gramList = new ArrayList<GramDO>();
		
		    
		return null;
}

/**
 * 
 * @param searchIndex 需要检索的字段
 * @param keyword  关键词
 * @return List bars 
 * @throws Exception
 */
/*
private List<GramDO> searchQueryGram(String searchIndex[],QueryDO queryDO) throws Exception{
		List<GramDO> gramList = new ArrayList<GramDO>();
		 //搜索的关键字段名
		File indexfile =null;
		String highString =null;
		Directory directory= null;
		IndexSearcher indexSearcher=null;
		int startNum =0; //开始的条数
		int endNum =0;//结束的条数
		int totalItem=0;//总条数
		//Map <String,BarDO>tempUserMap = new HashMap();
	try{	
		//lucene 3.0 获取索引文件路径
		
		if(gameIndexPath !=null) {
			indexfile = new File(gameIndexPath);
			directory  = FSDirectory.open(indexfile); 
		}
	 //建立索引搜索
	   indexSearcher = new IndexSearcher(directory,true);
	 //获取庖丁解牛的分词器
	   Analyzer analyzer = new PaodingAnalyzer();
	  
	 // 创建解析器 ，可以对多个字段进行索引
       QueryParser parser = new  MultiFieldQueryParser(Version.LUCENE_31, searchIndex, analyzer);
       
       //高亮显示设置高亮的格式
       SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter(
           "<font color=#FF0000>", "</font>");

	 //获取查找对象   
	    Query query = parser.parse(queryDO.getKeyword());// 获取查询对象 
	    Highlighter highlighter = new Highlighter(simpleHTMLFormatter,new QueryScorer(query));
	    //这个100是指定关键字字符串的context的长度，你可以自己设定，因为不可能返回整篇正文内容
	    highlighter.setTextFragmenter(new SimpleFragmenter(100));
	    TopScoreDocCollector results = TopScoreDocCollector.create(10, false);
	    //获取索引的对象 按最后更新时间进行倒叙 
	    TopDocs ts = indexSearcher.search(query,Constants.LUCENE_SEARCH_MAXITEM,new Sort(new SortField(SORT_KEY, SortField.STRING, true)));
	    
	 
	    if(ts !=null && ts.totalHits>0){
	    	ScoreDoc[] hits = ts.scoreDocs;  //老版本中 Hits --length  
	    	totalItem = ts.totalHits;
	    	if(totalItem > Constants.LUCENE_SEARCH_MAXITEM){
		    	totalItem = Constants.LUCENE_SEARCH_MAXITEM;
		    }
	    	queryDO.setTotalItem(totalItem);
	    	queryDO.validatePageInfo();
	    	//分页获取开始的条数
			 startNum =( queryDO.getToPage()-1)*queryDO.getPerPageSize();
			 //结束的数量
			 endNum = queryDO.getToPage()* queryDO.getPerPageSize();
			 if(endNum >=hits.length )endNum = hits.length;		
			 
			 for (int i= startNum;i < endNum; i++) {           
	                    Document hitDoc = indexSearcher.doc(hits[i].doc); 
	                    
	                    if (hitDoc !=null ){
	                    	GramDO gram = new  GramDO();
	                    	gram.setId(Long.valueOf(hitDoc.get("BARID")));

	                    	//初始化高亮显示	                    	
	                    	highString = setHighlighter(hitDoc.get("VNAME"),queryDO.getKeyword(),highlighter,analyzer);
	                    	gram.setVname(highString);
	                    	gram.setMoney(hitDoc.get("MONEY"));
	                    	gram.setAverage(hitDoc.get("AVERAGE"));
	                    	gram.setUtime(DateTimeUtil.getFormatDateTime(hitDoc.get("MODIFIEDTIME")));
	                    	//gram.setTotalItem(totalItem);
	                    	//tempUserMap.put(String.valueOf(hitDoc.get("CREATEID"))+i, bar);
	                    	//System.out.println("key:"+String.valueOf(hitDoc.get("CREATEID"))+i  +"name :"+bar.getName());
	                    	gramList.add(gram);	                    	
	                    }	                    	                    
	            } 
			 
			 
			 
				
		
	    }  
	    
	}catch(Exception e){
		log.error("SearchQueryBOImpl: SEARCH GRAM BY VNAME FAIL:", e);
		throw e;
	}finally{
		if(indexSearcher!=null)indexSearcher.close();
	}
	    return gramList;
}
*/

	
	/**
	   *
	   * @param content 需要处理高亮的内容
	   * @param keyword 查找范围的关键字
	   * @param highlighter 高亮处理类
	   * @param analyzer 高亮处理类
	   * @return 返回处理过后的内容(要是内容中不包含关键子就会返回 null)
	   * @throws java.lang.Exception
	   */
/*
 private  String setHighlighter(String content, String keyword,
	                                Highlighter highlighter, Analyzer analyzer) throws Exception {
	    String temp = content;
	 
	   
	    if (content != null) {
	    	//如果是存英文或者数字就用lucene自带的分词器	    	
	      TokenStream tokenStreamTitle = analyzer.tokenStream(keyword, new StringReader(temp));
	      temp = highlighter.getBestFragment(tokenStreamTitle, temp);
	    }
	    //要是返回为null的话,就默认为原来的内容.
	    if(temp == null){
	       temp = content;
	    }
	    return temp;
	  }	
	  */
}
